package org.example;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.Base64;


public class Base64Util {
    /**
     * 获取待处理文件内容的Base64编码
     *
     * @param filePath 待处理文件路径
     * @return 文件内容的Base64编码
     * @throws IOException IO异常
     */
    public static String getFileContentAsBase64(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = null;
        byte[] fileContent = new byte[(int) file.length()];
        try {
            fis = new FileInputStream(file);
            fis.read(fileContent);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        String imgStr = Base64.getEncoder().encodeToString(fileContent);

        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        return imgParam;
    }

    /**
     * Base64字符串转图片
     *
     * @param base64String
     * @param imageFileName
     */
    public static void convertBase64StrToImage(String base64String, String imageFileName) {
        ByteArrayInputStream bais = null;
        try {
            //获取图片类型
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //获取JDK8里的解码器Base64.Decoder,将base64字符串转为字节数组
            byte[] bytes = Base64.getDecoder().decode(base64String);
            //构建字节数组输入流
            bais = new ByteArrayInputStream(bytes);
            //通过ImageIO把字节数组输入流转为BufferedImage
            BufferedImage bufferedImage = ImageIO.read(bais);
            //构建文件
            File imageFile = new File(imageFileName);
            //写入生成文件
            ImageIO.write(bufferedImage, suffix, imageFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
